package com.example.test622.login

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class LoginViewModel:BaseViewModel<LoginIntent,LoginState>() {
	init {
		viewModelScope.launch {
			intent.consumeAsFlow().collect{
				when(it){
					is LoginIntent.Login->login(it.password,it.username)
				}
			}
		}
	}
	
	private suspend fun login(password: String, username: String) {
		val s = try {
			val res = service.login(password, username)
			if(res.code == 0){
				LoginState.LoginSuccess(res)
			}else{
				LoginState.LoginFailed(res.msg)
			}
		}catch (e:Exception){
			LoginState.LoginFailed(e.message?:"")
		}
		state.postValue(s)
	}
}